<?php

namespace App\Admin\Controllers;

use App\Models\Merchant\Gift;

use App\Models\Merchant\GiftLog;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;

class GiftController extends Controller
{
    use ModelForm;
    const CATEGORY=[
        1=>'增加金币',
        2=>'增加积分',
        3=>'兑换车辆',
        4=>'实物领取',
        5=>'虚拟物品',
    ];

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('礼物管理');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('礼物管理');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('礼物管理');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Gift::class, function (Grid $grid) {

            $grid->model()->withoutGlobalScopes()->orderByDesc('sort')->orderByDesc('id');
            $grid->id('ID')->sortable();
            $grid->sort('排序')->editable();
            $grid->name('名称');
            $grid->img('图片')->image('',50,50);
            $grid->desc('描述');
            $grid->category('类型')->display(function($category){
               return self::CATEGORY[$category];
            });
            $grid->begin_datetime('投放开始时间');
            $grid->end_datetime('投放结束时间');
            $all_stock = Gift::valid()->sum('stock');
//            $grid->stock('剩余库存(概率)')->display(function($stock)use($all_stock){
//                $rate = $all_stock>0?round($stock/$all_stock,2)*100:0;
//                return $stock.' ( '.$rate.'%)';
//            });
            $grid->stock('剩余库存');
            $grid->rand('概率')->display(function($rand){
               if($rand>0)
                return $rand.'%';
               else
                   return '';
            });
            $grid->is_open('是否开启')->switch();
            $grid->show('是否展示')->switch();
    
            $grid->actions(function($actions){
                $actions->prepend('<a href="'.'gift/'.$actions->getKey().'/logs'.'" title="查看记录"><i class="fa fa-bars"></i></a>');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Gift::class, function (Form $form) {
            $total = Gift::valid()->where('stock','>', 0)->sum('rand');

            $form->hidden('id', 'ID');
            $form->number('sort','排序')->default(0);
            $form->text('name','名称')->rules('required');
            $form->text('desc','描述')->rules('required');
            $form->image('img','图片');
            $form->radio('category','类型')->options(self::CATEGORY)->rules('required');
            $form->text('item','对象ID或数量');
            $form->datetimeRange('begin_datetime','end_datetime','投放有效期');
            $form->number('stock','库存');
            $form->number('rand','概率')->help('当前礼品总概率为：'.$total.'%')
                ->rules('required|numeric|max:100',['max'=>'礼品总概率不能大于100%']);;
            $form->switch('is_open','是否开启');
            $form->switch('show','是否展示')->default(0);

            $form->saving(function ($form) {
                $current_rand = Gift::valid()->where('stock','>', 0)->where('id','<>',$form->id)->sum('rand');
                if($current_rand + $form->rand > 100){
                    $error = new MessageBag([
                        'title'   => '保存失败,所有礼品抽取概率超过了100%',
                    ]);
                    return back()->with(compact('error'));
                }

            });
        });
    }
    
    public function destroy($id)
    {
        //删除前的判断
        //if(GiftLog::unsended()->unused()->where('merchant_gift_id',$id)->exists()){
        //    return response()->json([
        //        'status'  => false,
        //        'message' => '删除失败，还有相关记录未删除',
        //    ]);
        //}
        if ($this->form()->destroy($id)) {
            GiftLog::where('merchant_gift_id',$id)->delete();
            return response()->json([
                'status'  => true,
                'message' => trans('admin.delete_succeeded').'已删除相关记录',
            ]);
        } else {
            return response()->json([
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ]);
        }
    }
}
